package com.flyoil.petromp.ui.activity.activity_me;

import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.cnpc.fyimageloader.glide.GlideHelper;
import com.cnpc.fyimageloader.utils.ImageTools;
import com.cnpc.fyimageloader.utils.ImageUtils;
import com.cnpc.fyimageloader.utils.PhotoUtil;
import com.cnpc.fyutils.ToastUtils;
import com.cnpc.fyviewlibrary.view.CircleImageView;
import com.flyoil.petromp.Constant.ConstantNetworkCode;
import com.flyoil.petromp.R;
import com.flyoil.petromp.apiservice.HttpModel;
import com.flyoil.petromp.apiservice.OnObserverRetrofitResetCallBack;
import com.flyoil.petromp.base.BaseActivity;
import com.flyoil.petromp.base.BaseEntity;
import com.flyoil.petromp.base.MyApplication;
import com.flyoil.petromp.entity.entity_me.UserPhoneEntity;
import com.flyoil.petromp.utils.ApplicationHelp;
import com.flyoil.petromp.utils.Dialog.Dialog_util;
import com.flyoil.petromp.utils.HintConstants;
import com.flyoil.petromp.utils.MoccaPreferences;
import com.flyoil.petromp.utils.PermissionUtils;
import com.flyoil.petromp.utils.RequestBody_Util;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import okhttp3.RequestBody;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 修改头像的界面
 */
public class SetHeadActivity extends BaseActivity {
    private ImageView img_back;
    private CircleImageView img_head;
    private PopupWindow popupWindow;
    private File file_head;

    @Override
    protected int getContentViewResId() {
        return R.layout.activity_set_head;
    }

    @Override
    protected void initViews() {
        super.initViews();
        httpModel = new HttpModel();
        img_back = $(R.id.img_title_back);
        img_head = $(R.id.img_set_head);
        GlideHelper.showImage(mContext, MoccaPreferences.user_avatar.get(), img_head, R.mipmap.user_head_icon);
    }

    @Override
    protected void initEvents() {
        super.initEvents();
        img_back.setOnClickListener(onClickListener);
        img_head.setOnClickListener(onClickListener);

    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.img_title_back:
                    backFinish();
                    break;
                case R.id.img_set_head:
                    showPhoto();
                    break;
                case R.id.tv_popup_photo_takephoto:// 拍照按钮
                    closePopWindow();
                    takePhoto();
                    break;
                case R.id.tv_popup_photoalbum:// 相册按钮
                    closePopWindow();
                    pickAlbum();
                    break;
                case R.id.tv_popup_photo_cancle:// 取消按钮
                    closePopWindow();
                    break;
            }
        }
    };
    /**
     * 纸质签名去调用相机 需要两个权限
     */
    private static final String[] requestPermissions = {
            PermissionUtils.PERMISSION_CAMERA,
            PermissionUtils.PERMISSION_WRITE_EXTERNAL_STORAGE,
            PermissionUtils.PERMISSION_READ_EXTERNAL_STORAGE
    };

    private void takePhoto() {
        PermissionUtils.requestMultiPermissions(this, requestPermissions, new PermissionUtils.PermissionGrant() {
            @Override
            public void onPermissionGranted(int requestCode) {
                closePopWindow();
                ImageUtils.pickImageFromCamera(mContext, ImageUtils.REQUEST_CODE_FROM_CAMERA);
            }
        });

    }

    private void pickAlbum() {
        PermissionUtils.requestPermission(this, PermissionUtils.CODE_READ_EXTERNAL_STORAGE, new PermissionUtils.PermissionGrant() {

            @Override
            public void onPermissionGranted(int requestCode) {
                closePopWindow();
                ImageUtils.pickImageFromAlbum(mContext);
            }
        });
    }

    private void initBitmap(Uri uri) {
        Dialog_util.start_NetworkRequests_diolog(this);
        ImageUtils.compressWidthImage(this, ImageUtils.getImageAbsolutePath19(mContext, uri), ((WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getWidth())
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<byte[]>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        Dialog_util.close_NetworkRequests_diolog();
                        Toast.makeText(mContext, "图片错误，请重拍！", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onNext(byte[] bytes) {
                        Dialog_util.close_NetworkRequests_diolog();
                        img_head.setImageBitmap(ImageTools.byteToBitmap(bytes));
                        file_head = PhotoUtil.compress_bitmap(ImageTools.byteToBitmap(bytes), Environment.getExternalStorageDirectory() + "/image" + "usericonhead.jpg");
                        uploadAvatar();
                    }
                });
    }

    /**
     * 上传头像
     */
    private void uploadAvatar() {
        Map<String, RequestBody> map = new HashMap<>();
        map.put(RequestBody_Util.parseImageMapKey("file", file_head.getName()), RequestBody_Util.parseRequestBody_File(file_head));
//        map.put(RequestBody_Util.parseImageMapKey("carImage", file_head.getName()), RequestBody_Util.parseRequestBody_File(file_head));
        httpModel.uploadAvatar(map, new OnObserverRetrofitResetCallBack<BaseEntity>() {

            @Override
            public void onSuccess(BaseEntity model) {
                ToastUtils.show_toast(model.getMessage());
                Dialog_util.close_NetworkRequests_diolog();
                UserPhoneEntity entity = null;
                if (model instanceof UserPhoneEntity) {
                    entity = (UserPhoneEntity) model;
                }
                if (entity != null && entity.getCode() == ConstantNetworkCode.SuccedCode && entity.getData() != null) {
                    MoccaPreferences.user_avatar.put(entity.getData().getUrl());
                }
            }

            @Override
            public void onFailure(String msg) {
            }
        });


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

            if (requestCode == ImageUtils.REQUEST_CODE_FROM_CAMERA) {//拍照返回
//                initBitmap(ImageUtils.imageUriFromCamera);
                ImageUtils.cropImage(mContext, ImageUtils.imageUriFromCamera);
            } else if (requestCode == ImageUtils.REQUEST_CODE_FROM_ALBUM) {//相册返回
//                initBitmap(data.getData());
                ImageUtils.cropImage(mContext, data.getData());
            } else if (requestCode == ImageUtils.REQUEST_CODE_CROP_IMAGE) {//裁剪返回
                initBitmap(ImageUtils.imageUriFromCamera);
            }
        }

    }

    /**
     * 显示选择框
     */
    private void showPhoto() {
        final View view_backgroud = $(R.id.view_background);
        View v1 = LayoutInflater.from(this).inflate(R.layout.popup_photo_select, null);// 创建view
        popupWindow = new PopupWindow(v1, ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT, true);// 实例化popupwindow的方法
        popupWindow.setBackgroundDrawable(new ColorDrawable());
        // 这个方法是为了当点击除了popupwindow的其他区域可以关闭popupwindow的方法
        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setAnimationStyle(R.style.popwin_anim_style);
        popupWindow.showAtLocation(img_head, Gravity.BOTTOM, 0, 0);
        view_backgroud.setVisibility(View.VISIBLE);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                view_backgroud.setVisibility(View.GONE);
            }
        });

        TextView tv_takephoto = (TextView) v1.findViewById(R.id.tv_popup_photo_takephoto);

        TextView tv_album = (TextView) v1.findViewById(R.id.tv_popup_photoalbum);

        TextView tv_cancle = (TextView) v1.findViewById(R.id.tv_popup_photo_cancle);

        tv_takephoto.setOnClickListener(onClickListener);
        tv_album.setOnClickListener(onClickListener);
        tv_cancle.setOnClickListener(onClickListener);
    }

    /**
     * 关闭popup
     */
    private void closePopWindow() {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionUtils.requestPermissionsResult(this, requestCode, permissions, grantResults, new PermissionUtils.PermissionGrant() {
            @Override
            public void onPermissionGranted(int requestCode) {
                switch (requestCode) {
                    case PermissionUtils.CODE_MULTI_PERMISSION:
                        closePopWindow();
                        ImageUtils.pickImageFromCamera(mContext, ImageUtils.REQUEST_CODE_FROM_CAMERA);
                        break;
                    case PermissionUtils.CODE_READ_EXTERNAL_STORAGE:
                        closePopWindow();
                        ImageUtils.pickImageFromAlbum(mContext);
                        break;
                    default:
                        break;
                }
            }
        });
    }
}
